<template>
  <div class="message-page">
    <!-- 左侧侧边栏 -->
    <aside class="message-aside">
      <h3 class="message-aside__title">最近消息</h3>

      <!-- 会话列表 -->
      <div class="message-aside__list">
        <button
          class="message-item"
          v-for="item in messageList"
          :key="item.sessionId"
          @click="handleMessageClick(item.sessionId)"
        >
          <div class="avatar-wrapper">
            <img :src="item.avatar" class="avatar" />
            <span v-if="item.unreadCount > 0" class="badge">{{
              item.unreadCount
            }}</span>
          </div>
          <div class="content">
            <div class="top-row">
              <div class="title">{{ item.userName || '好友' }}</div>
            </div>
            <div class="message-bottom">
              <div class="message">{{ item.lastMessage }}</div>
              <div class="time" v-if="item.postTime">
                {{ formatTime(item.postTime) }}
              </div>
            </div>
          </div>
        </button>
      </div>
    </aside>

    <!-- 中间分割线 -->
    <div class="message-split-line"></div>

    <!-- 右侧内容区域 -->
    <section class="message-content">
      <template v-if="activeMessageId === -1">
        <!-- 右侧 tab 列表 -->
        <div class="slide-tab">
          <button
            v-for="tab in rightTabs"
            :key="tab"
            :class="['slide-tab__tab-item', { active: tab === rightActiveTab }]"
            @click="handleTabChange(tab)"
          >
            <div class="slide-tab__tab-label" style="position: relative">
              {{ tab }}
              <span v-if="unreadCounts[tab] > 0" class="number-badge">
                {{ unreadCounts[tab] }}
              </span>
            </div>
          </button>
        </div>

        <component :is="currentRightComponent" v-if="currentRightComponent" />
        <div class="message-list-empty" v-else>暂无更多内容</div>
      </template>

      <template v-else>
        <Chat
          :sessionId="activeMessageId"
          :userName="currentUserName"
          :targetId="currentTargetId"
        />
      </template>
    </section>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { getMessageById, updateSession } from '@/apis/message'
import { useAccountStore } from '@/stores/useAccountStore'
import CommentNotice from './CommentNotice.vue'
import LikesNotice from './LikesNotice.vue'
import FollowNotice from './FollowNotice.vue'
import Chat from './Chat.vue'
import { getNoticeCount, updateNotice } from '@/apis/notice'
import { useMessageStore } from '@/stores/messageStore'
import { useRouter, useRoute } from 'vue-router'
const messageStore = useMessageStore()
const router = useRouter()
const route = useRoute()

// 当前选中的消息会话 ID，默认展示互动消息
const activeMessageId = ref(-1)
const currentUserName = ref('')
const interactionUnreadTotal = ref(0)
// 互动消息固定项
const interactionItem = computed(() => ({
  sessionId: -1,
  userName: '互动消息',
  lastMessage: '近期活动消息',
  avatar:
    'https://imgheybox.max-c.com/dev/bbs/2024/12/16/35dc7bc7c0074df0ae80809865dea269.png',
  postTime: null,
  unreadCount: interactionUnreadTotal.value, // ✅ 响应式绑定
}))

// 登录用户信息
const accountStore = useAccountStore()
const uid = accountStore.uid

// 好友会话列表
const friendChatList = ref([])

onMounted(async () => {
  try {
    const [res1, res2] = await Promise.all([
      getMessageById(uid),
      getNoticeCount(uid),
    ])

    // 会话数据
    if (res1?.code === '200' && Array.isArray(res1.data)) {
      friendChatList.value = res1.data
    }

    // 互动通知未读数
    if (res2?.code === '200') {
      const { commentCount, likesCount, followCount } = res2.data
      unreadCounts.value = {
        评论: commentCount,
        赞: likesCount,
        关注: followCount,
      }
      interactionUnreadTotal.value = commentCount + likesCount + followCount
    }
  } catch (err) {
    console.error('获取消息或通知失败', err)
  }

  await messageStore.loadSessions(uid)

  // 处理直接通过URL打开会话的情况
  if (route.query.sessionId) {
    const session = messageStore.sessions.find(
      (s) => s.sessionId == route.query.sessionId
    )
    if (session) handleMessageClick(session.sessionId)
  }
})
const handleTabChange = async (tab) => {
  rightActiveTab.value = tab

  const unread = unreadCounts.value[tab]
  if (unread > 0) {
    try {
      const type = tabTypeMap[tab]
      const res = await updateNotice(type, uid)

      // 仅当返回的 message 是 '200' 时才更新本地状态
      if (res?.code === '200') {
        unreadCounts.value[tab] = 0
        interactionUnreadTotal.value = Math.max(
          interactionUnreadTotal.value - unread,
          0
        )
      } else {
        console.warn(`未读清除失败`, res)
      }
    } catch (err) {
      console.error(`更新 ${tab} 未读数失败`, err)
    }
  }
}

// 整体展示列表
const messageList = computed(() => [
  interactionItem.value,
  ...messageStore.sessions,
])

// tab 切换
const rightTabs = ['评论', '赞', '关注']
const rightActiveTab = ref(null)
const tabTypeMap = {
  评论: 2,
  赞: 1,
  关注: 3,
}

const tabComponentMap = {
  评论: CommentNotice,
  赞: LikesNotice,
  关注: FollowNotice,
}
const unreadCounts = ref({
  评论: 0,
  赞: 0,
  关注: 0,
})

const currentRightComponent = computed(
  () => tabComponentMap[rightActiveTab.value]
)

// 点击消息项
const currentTargetId = ref(null)
const handleMessageClick = async (id) => {
  activeMessageId.value = id

  if (id === -1) {
    rightActiveTab.value = '评论'
    currentUserName.value = ''
    currentTargetId.value = null
  } else {
    const user = messageList.value.find((item) => item.sessionId === id)
    currentUserName.value = user?.userName || '好友'
    currentTargetId.value = user?.senderId || null

    // ✅ 调用接口清除未读
    try {
      await updateSession(id, uid)
      if (user) user.unreadCount = 0 // ✅ 本地同步清空
    } catch (err) {
      console.error('清除未读数失败', err)
    }
  }
}

// 时间格式化
function formatTime(datetime) {
  if (!datetime) return ''
  const date = new Date(datetime)
  const now = new Date()
  const diff = Math.floor((now - date) / 1000)
  if (diff < 60) return '刚刚'
  if (diff < 3600) return `${Math.floor(diff / 60)}分钟前`
  if (diff < 86400) return `${Math.floor(diff / 3600)}小时前`
  return date.toLocaleDateString()
}
</script>

<style scoped>
.message-page {
  display: flex;
  background: #fff;
  min-height: 600px;
  border: 1px solid #eee;
}

.message-aside {
  width: 300px;
  padding: 16px;
  border-right: 1px solid #eee;
  display: flex;
  flex-direction: column;
}

.slide-tab {
  display: flex;
  position: relative;
  margin-bottom: 12px;
}
.slide-tab__tab-item {
  background: none;
  border: none;
  padding: 8px 12px;
  font-size: 14px;
  cursor: pointer;
}
.slide-tab__tab-item.active .slide-tab__tab-label {
  font-weight: bold;
  color: #333;
}
.slide-tab-tab__bar {
  position: absolute;
  bottom: 0;
  background-color: #409eff;
  transition: all 0.3s;
}

.message-aside__search-box {
  margin: 10px 0;
}
.message-aside__search-wrapper {
  display: flex;
  align-items: center;
  background: #f5f5f5;
  border-radius: 4px;
  padding: 4px 8px;
}
.message-aside__search-input {
  border: none;
  outline: none;
  background: transparent;
  margin-left: 6px;
  flex: 1;
}

.message-aside__list {
  flex: 1;
  overflow-y: auto;
}
.message-item {
  display: flex;
  padding: 10px;
  border-radius: 6px;
  transition: background 0.2s;
  width: 100%;
  border: none;
  background: transparent;
  cursor: pointer;
}
.message-item:hover {
  background-color: #f0f0f0;
}
.avatar-wrapper {
  margin-right: 10px;
}
.avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
}
.content {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
}
.top-row {
  display: flex;
  align-items: center;
  margin-bottom: 4px;
}
.title {
  font-weight: bold;
  font-size: 14px;
  color: #333;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.message-bottom {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.message {
  font-size: 13px;
  color: #666;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.time {
  font-size: 12px;
  color: #999;
  margin-left: 12px;
  white-space: nowrap;
  flex-shrink: 0;
}
.message-split-line {
  width: 1px;
  background-color: #eee;
}
.message-content {
  flex: 1;
  padding: 16px;
}
.message-list-empty {
  margin-top: 20px;
  text-align: center;
  color: #999;
}
.badge {
  position: absolute;
  top: -2px;
  right: -2px;
  background-color: red;
  color: white;
  font-size: 10px;
  border-radius: 50%;
  padding: 2px 6px;
  line-height: 1;
}

.avatar-wrapper {
  position: relative; /* 保证红点绝对定位在头像上 */
  margin-right: 10px;
}

.dot-badge {
  display: inline-block;
  width: 6px;
  height: 6px;
  background-color: red;
  border-radius: 50%;
  margin-left: 4px;
}

.number-badge {
  position: absolute;
  top: -6px;
  right: -10px;
  background-color: red;
  color: white;
  font-size: 10px;
  min-width: 16px;
  height: 16px;
  line-height: 16px;
  text-align: center;
  border-radius: 8px;
  padding: 0 4px;
  box-shadow: 0 0 0 1px #fff; /* 可选：白边增强可读性 */
}
</style>
